package com.androidhive.httprequests;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.LinearLayout;
import android.R.color;
import android.content.Intent;
import android.net.NetworkInfo;
import android.net.Uri;
import android.content.ContentValues;
import android.net.ConnectivityManager;





public class AndroidHTTPRequestsActivity extends Activity {
	
	String str = "";
	
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		boolean checknet = isNetworkAvailable();
		 Toast.makeText(getApplicationContext(),String.valueOf(checknet),Toast.LENGTH_LONG).show();
		Context mContext = getBaseContext();
		DisplayMetrics displayMetrics = new DisplayMetrics(); 
		displayMetrics = mContext.getResources().getDisplayMetrics();
		int mScreenWidth = displayMetrics.widthPixels;
		int mSreenHeight = displayMetrics.heightPixels;
		LinearLayout ll1 = (LinearLayout) findViewById(R.id.ll2);
	
		// Creating HTTP client
		HttpClient httpClient = new DefaultHttpClient();
		// Creating HTTP Post
		HttpPost httpPost = new HttpPost(
				"https://www.tnebnet.org/awp/logincheck");

		// Building post parameters
		// key and value pair
		List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
		nameValuePair.add(new BasicNameValuePair("j_username", "sathish25026"));
		nameValuePair.add(new BasicNameValuePair("j_password","0189017101900178017901890178012301240125"));

		// Url Encoding the POST parameters
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
		} catch (UnsupportedEncodingException e) {
			// writing error to Log
			e.printStackTrace();
		}

		// Making HTTP Request
		try {
			HttpResponse response = httpClient.execute(httpPost);
			//HTML = EntityUtils.toString(response.getEntity());
			BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
			 File myFile = new File("/sdcard/"+"Ktest.txt");
			 myFile.createNewFile();
			 FileOutputStream fOut = new FileOutputStream(myFile);
				OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
			//System.out.println(EntityUtils.toString(response.getEntity()));
			 
			 String line = "";
			
			
			 
		      while ((line = rd.readLine()) != null) {
		    	  myOutWriter.append(line);
      	    	//System.out.println(line);
                      
		       
		      }
		      
		    	myOutWriter.close();
				fOut.close();
		   
		    Toast.makeText(getApplicationContext(),"Ktest.txt" + " saved",Toast.LENGTH_LONG).show();
		    try {
		         //Document doc = Jsoup.connect(html).get();
		    	System.out.println("-------kkkkkkkkkkkkkk-----------" + checknet);
		    	File myFile1 = new File("/sdcard/"+"Ktest.txt");
		    	   Document doc = Jsoup.parse(myFile1, "UTF-8", "http://example.com/");
		         Elements tableElements = doc.select("table");

		         Elements tableHeaderEles = tableElements.select("thead tr th");
		         System.out.println("headers");
		         for (int i = 0; i < tableHeaderEles.size(); i++) {
		            System.out.println(tableHeaderEles.get(i).text());
		         }
		         System.out.println();

		         Elements tableRowElements = tableElements.select(":not(thead) tr");

		         for (int i = 0; i < tableRowElements.size(); i++) {
		            Element row = tableRowElements.get(i);
		            System.out.println("-------row--------");
		            Elements rowItems = row.select("td");
		            final TextView rowTextView1 = new TextView(this);
		           
		            for (int j = 0; j < rowItems.size(); j++) {
		            	
		            	 final TextView rowTextView = new TextView(this);
		            	if(j==0)
		            	rowTextView.setText("Consumer No : " + rowItems.get(j).text());
		            	if(j==1)
			            	rowTextView.setText("Customer Name : " + rowItems.get(j).text());
		            	if(j==3){
			            	rowTextView.setText("Bill Amt(Rs.) : " + rowItems.get(j).text());
			            	if(rowItems.get(j).text().equals("Rs.Nil"))
			            	   rowTextView.setTextColor(getResources().getColor(R.color.gc));	
			            	else
			            		rowTextView.setTextColor(getResources().getColor(R.color.errorColor));	
		            	}
		            	if(j==4  )
		            	{
		            		rowTextView.setText("Due Date " + rowItems.get(j).text());
		            	}
		            	if(j != 2)
		            	{
		            				            		
		            		ll1.addView(rowTextView);
		            	}
		            	
		            	System.out.println("---------jjjjjjjjjjjj-------"+j);
		               System.out.println(rowItems.get(j).text());
		            }
		            
		            rowTextView1.setText("-----------------------");
            		
		         }

		      } catch (IOException e) {
		         e.printStackTrace();
		      } 
		    
			// writing response to log
			System.out.println(response);
			Log.i("Http Response:", response.toString());
		} catch (ClientProtocolException e) {
			// writing exception to log
			e.printStackTrace();
		} catch (IOException e) {
			// writing exception to log
			e.printStackTrace();

		}
	}
	
	private boolean isNetworkAvailable() {
	    ConnectivityManager connectivityManager 
	          = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
	    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
	    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
	}
}